package com.dy.lock.screen.api.scoket;

import java.io.BufferedWriter;
import java.io.OutputStreamWriter;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.nio.charset.Charset;
import java.util.Scanner;
import java.util.concurrent.Callable;

import org.apache.log4j.Logger;

public class SocketClient implements Callable<String> {
	private static final Logger log = Logger.getLogger(SocketClient.class);
	private String ip;
	private int port;

	public String getIp() {
		return ip;
	}

	public SocketClient(String ip, int port, String message) {
		super();
		this.ip = ip;
		this.port = port;
		this.message = message;
	}

	public void setIp(String ip) {
		this.ip = ip;
	}

	public int getPort() {
		return port;
	}

	public void setPort(int port) {
		this.port = port;
	}

	private String message;

	public String getMessage() {
		return message;
	}

	public static String sendMessage(String ip, int port, String message) {
		Socket sc = null;
		try {
			// 打开Socket通道
			sc = new Socket();
			sc.connect(new InetSocketAddress(ip, port), 2000);
			sc.setSoTimeout(30000);
			sc.setKeepAlive(true);
			Charset charset = Charset.forName("UTF-8");
			if (message != null && message.trim().length() > 0) {
				BufferedWriter writer = new BufferedWriter(
						new OutputStreamWriter(sc.getOutputStream(), charset));
				if (log.isInfoEnabled())
					log.info("发送数据到：" + ip + "端口：" + port + ":" + message);
				writer.write(message.trim());
				writer.newLine();
				writer.flush();
			}
			Scanner scan = new Scanner(sc.getInputStream(), charset.name());
			StringBuilder sb = new StringBuilder();
			while (scan.hasNextLine()) {
				sb.append(scan.nextLine());
			}
			sc.getOutputStream().close();
			scan.close();
			sc.close();
			if (log.isInfoEnabled())
				log.info(ip + "端口：" + port + ",响应数据：" + sb.toString());
			return sb.toString();
		} catch (Exception e) {
			if (sc != null && !sc.isClosed())
				try {
					sc.close();
				} catch (Exception e1) {
				}
			sc = null;
		}
		return null;
	}

	public void setMessage(String message) {
		this.message = message;
	}

	public String call() throws Exception {
		return sendMessage(ip, port, message);
	}
}
